import axios from 'axios'
import { Message } from 'element-ui'
const install = (Vue, vm) => {


  Vue.prototype.$http = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, 
    timeout: 30*1000,
    validateStatus: function (status) {
      return status >= 200 && status <= 500
    }
  })

  Vue.prototype.$http.interceptors.request.use(
    config => {
      config.headers['Project-Id'] = 63
      //config.headers['Project-Id'] = vm.vuex_project ? JSON.parse(vm.vuex_project).deptId : 1
      if(vm.userInfo){
        let user = vm.userInfo
        config.headers.Authorization = 'bearer ' + user.access_token;
        config.headers['TENANT-ID'] = user.user_info ? user.user_info.tenantId : 1;
      }


      if(config.url.indexOf('/auth/oauth/token')>=0){
        config.headers.isToken = false;
        config.headers.Authorization = "Basic cGlnOnBpZw==";
      }
      
      return config;
    },
    error => {
      return Promise.reject(error)
    }
  )

  Vue.prototype.$http.interceptors.response.use(
    response => {
      if(response.status == 200){
        const res = response.data
        if(res.user_info){
          return res
        }
        if(res.code == 0){
          return res.data ? res.data : res;
        }
        Message({
          message: res.msg,
          type: 'error',
          duration: 2000
        })
        return Promise.reject(res.msg)
      }else if(response.status == 401){
        console.log(vm)
        vm.$router.push({
          path:'/login'
        })
        return false;
      }else{
        return Promise.reject(response.statusText)
      }
    },
    error => {
      Message({
        message: error.statusText,
        type: 'error',
        duration: 2 * 1000
      })
      return Promise.reject(error)
    }
  )
}

export default {
	install
}